package cn.hzu580.interceptor;

import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import cn.hzu580.entity.Log;
import cn.hzu580.entity.User;
import cn.hzu580.service.LogService;
import cn.hzu580.service.UserService;
import cn.hzu580.util.DateUtil;
import cn.hzu580.vo.UserVO;

public class LogsInterceptor extends MethodFilterInterceptor{

	@Resource(name="user")
	private UserService userService;
	
	@Resource(name="log")
	private LogService logService;
	
	
	@Override
	protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse resp = ServletActionContext.getResponse();
		String session_id = request.getSession().getId();
		User operator = null;
		String uid = (String) request.getSession().getAttribute("uid");
		if(uid != null && !uid.equals("")){
			UserVO vo = new UserVO();
			vo.setUid(uid);
			operator = userService.get(vo);
		}
		String method = request.getServletPath();
		String ip = request.getRemoteAddr();
		String parameters = "";
		for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
			parameters += entry.getKey()+"="+entry.getValue()[0]+"\n";
		}
		
		actionInvocation.invoke();
		
		Log log = new Log();
		log.setIp(ip);
		log.setMethod(method);
		log.setOperator(operator);
		log.setParameters(parameters);
		log.setResponse(resp.getStatus());
		log.setSession_id(session_id);
		log.setTime(DateUtil.now());
		logService.write(log);
		
		return Action.NONE;
	}
	
}
